/**
 * 设备导入
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, InputNumber, Select, message } from 'antd';
import { download } from '../../utils/browser';
import { isReleaseVersion } from '../../components/permissionControl';
import { exportQrcode, importDevice, api as apiPaths } from '../../services/device';
import { isSuccess } from '../../configs/error';

const Option = Select.Option;
const FormItem = Form.Item;

const styles = {
  title: {
    fontSize: '30px'
  },
  num: {
    background: '#108ee9',
    borderRusdio: '4px',
    color: '#fff',
    borderRadius: '4px',
    padding: '0 6px',
    marginRight: '10px',
    fontWeight: 700
  },
  mr: {
    marginRight: '1em'
  },
  input: {
    width: '10em'
  },
  right: {
    textAlign: 'right'
  },
  img: {
    width: '100%'
  },
  row: {
    padding: '1em 0',
    borderBottom: '1px solid #ccc'
  },
  p: {
    margin: '1em 0'
  },
  select: {
    width: '16em'
  }
};

class ImportPage extends Component {

  state = {
    loaded: 0,
    product: '',
    num: 100,
    isRelease: true
  }

  componentWillMount() {
    const { dispatch, user: { permissions = [] } } = this.props;
    const is = isReleaseVersion(permissions, apiPaths.exportQrcode);
    this.setState({ isRelease: is ? true : false });
    dispatch({
      type: 'productList/query'
    });
  }

  onFileChange = async (ev) => {
    // 上传
    const { isRelease } = this.state;
    const file = this.file.files[0];
    if (this.uploading) return;
    this.uploading = true;
    const { product } = this.state;
    const res = await importDevice(file, isRelease ? 0 : product, e => { });
    if (ev.target) {
      ev.target.value = '';
    }
    this.uploading = false;
    if (isSuccess(res)) {
      message.success('上传成功');
    }
  }

  uploading = false
  downloading = false

  createQr = async () => {
    const { isRelease } = this.state;
    const { user: { belongManufacturer } } = this.props;

    if (this.downloading) return;
    const { product, num } = this.state;
    if (belongManufacturer) { // 产商才需要判断
      if ((isRelease && !num) || (!product && isRelease)) {
        message.warning('请填写数量与选择产品');
        return;
      }
    }
    // if (!isRelease && !product) {
    // 	message.warning('请选择产品');
    // 	return;
    // }
    this.downloading = true;
    this.setState({ loaded: 0 });
    const res = await exportQrcode({ count: (isRelease && belongManufacturer) ? num : '1', productId: product }, e => {
      this.setState({ loaded: parseInt(e.loaded / 1024) });
    });
    this.downloading = false;
    this.setState({ loaded: 0 });
    if (res.data.type === 'application/json') {
      const reader = new FileReader();
      reader.onload = (e) => {
        isSuccess(JSON.parse(e.target.result));
      };
      reader.readAsText(res.data);
    } else {
      download(res.data, `模板.${(isRelease && belongManufacturer) ? 'zip' : 'zip'}`);
    }
  }

  importDevice = () => {
    const { isRelease, product } = this.state;
    const { user: { belongManufacturer } } = this.props;
    if (!product && !isRelease) {
      message.warn('请先选择产品!');
      return;
    }
    if (!belongManufacturer && isRelease && !product) {
      message.warn('请先选择产品!');
      return;
    }
    this.file.click();
  }

  render() {
    const { loaded, product, num } = this.state;
    const { productList, user: { permissions = [], belongManufacturer } } = this.props;
    const isRelease = isReleaseVersion(permissions, apiPaths.exportQrcode);
    return (
      <div className="content-inner">
        <div style={styles.right}>
          <Button onClick={() => history.back()}>返回</Button>
        </div>
        <Row gutter={16} style={styles.row}>
          <Col span={14}>
            <div style={styles.title}>
              <span style={styles.num}>01</span>
              {(isRelease && belongManufacturer) ? '生成二维码' : '下载模板'}
            </div>
            {
              (isRelease && belongManufacturer) ? <div>
                <p style={styles.p}>请选择生成二维码的数量，并点击“生成”，导出压缩包。压缩包里面包含若干的二维码图片，以及Excel模板表格</p>
                <Col span={12}>
                  <FormItem label="选择产品" required>
                    <Select style={styles.select} onChange={v => this.setState({ product: v })} value={product}>
                      {productList.map(p => <Option value={p.id}>{p.name}</Option>)}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="填写二维码数量（1-1000）" required>
                    <InputNumber
                      min={1}
                      max={1000}
                      step={100}
                      style={{ ...styles.input, ...styles.mr }}
                      value={num}
                      onChange={v => this.setState({ num: v })}
                    />
                    <Button type="primary" onClick={this.createQr}>{!loaded ? '生成' : `已下载${loaded}k`}</Button>
                  </FormItem>
                </Col>
              </div> :
                <div>
                  <p style={styles.p}>请选择对应的产品，下载导入模板</p>
                  <Col span={12}>
                    <Button type="primary" onClick={this.createQr}>{!loaded ? '生成' : `已下载${loaded}k`}</Button>
                  </Col>
                </div>
            }
          </Col>
          <Col span={10}>
            <img src={'http://www.fotor.com/images2/features/photo_effects/e_bw.jpg'} style={styles.img} />
          </Col>
        </Row>
        <Row gutter={16} style={styles.row}>
          <Col span={14}>
            <div style={styles.title}>
              <span style={styles.num}>02</span>
              匹配设备信息
						</div>
            <div>
              <p style={styles.p}>{`请在Excel模板表格记录${isRelease ? '二维码和设备mac的对应关系' : '所有信息'}`}</p>
            </div>
          </Col>
          <Col span={10}>
            <img src={'http://www.fotor.com/images2/features/photo_effects/e_bw.jpg'} style={styles.img} />
          </Col>
        </Row>
        <Row gutter={16} style={styles.row}>

          <Col span={14}>
            <div style={styles.title}>
              <span style={styles.num}>03</span>
              导入设备
						</div>
            <div>
              <p style={styles.p}>{isRelease ? '将已有设备mac和二维码对应关系的Excel' : '将已填写的Excel模板'}表格导入系统，点击“导入”，即可完成设备录入</p>
              {(!isRelease || !belongManufacturer) &&
                <FormItem label="选择产品" required>
                  <Select style={styles.select} onChange={v => this.setState({ product: v })} value={product}>
                    {productList.map(p => <Option value={p.id}>{p.name}</Option>)}
                  </Select>
                </FormItem>}
              <p>
                <Button type="primary" onClick={this.importDevice}>导入</Button>
                <input
                  type="file"
                  onChange={this.onFileChange}
                  style={{ display: 'none' }}
                  ref={d => this.file = d}
                />
              </p>
            </div>
          </Col>
          <Col span={10}>
            <img src={'http://www.fotor.com/images2/features/photo_effects/e_bw.jpg'} style={styles.img} />
          </Col>
        </Row>
      </div>
    );
  }
}

export default connect(({ productList, app }) => ({ productList: productList.list, user: app.user }))(ImportPage);
